from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import SKUImage
from .serializers import ImageSer
from sku.models import Good
from sku.serializers import GoodSer
from qiniu import Auth
# Create your views here.
class GetSkuImage(APIView):
    def get(self,request):
        page = int(request.query_params.get('page'))
        size = int(request.query_params.get('size'))
        data = SKUImage.objects.all()[((page-1)*size):(size*page)]
        ser = ImageSer(data,many=True)
        return Response({'data':ser.data,'count':SKUImage.objects.all().count()})

class GetOneImage(APIView):
    def get(self,request,id):
        try:
            data = SKUImage.objects.get(id=id)
            ser = ImageSer(data)
            return Response(ser.data)
        except Exception as e:
            print(e)
            return Response({'msg':'没有该数据','code':204})
    def delete(self,request,id):
        try:
            SKUImage.objects.get(id=id).delete()
            return Response({'msg':'删除成功','code':200})
        except Exception as e:
            print(e)
            return Response({'msg':'没有该数据','code':204})

class GetSku(APIView):
    def get(self,request):
        data = Good.objects.all()
        ser = GoodSer(data,many=True)
        return Response(ser.data)


#需要填写你的 Access Key 和 Secret Key
access_key = 'tZZ089D_Kl6B-APpiIB-orZ-7JEr_RRJB9UlkWhx'
secret_key = '-WkxSEURRgavdD9ZXV67XLvAsndjDFqBSKP-Cjwu'

class QiNiuFiles(APIView):
    def get(self,request):
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        bucket_name = "xiu-a"
        # 生成上传token,可以指定过期时间
        token = q.upload_token(bucket_name)
        return Response({'token':token})


class AddSkuImage(APIView):
    def post(self,request):
        sku = request.data.get('sku')
        image = request.data.get('image')
        try:
            SKUImage.objects.create(
                sku_id=sku,
                image=image
            )
            return Response({'msg': '图片添加成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg':'图片添加失败','code':204})

class PutSkuImage(APIView):
    def put(self,request,id):
        sku = request.data.get('sku')
        image = request.data.get('image')
        if type(sku) == int:
            sku_data = Good.objects.get(id = sku)
        else:
            sku_data = Good.objects.get(name=sku)
        try:
            data = SKUImage.objects.get(id=id)
            data.sku_id = sku_data.id
            data.image = image
            data.save()
            return Response({'msg': '图片修改成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg':'图片修改失败','code':204})